﻿using System;
using System.IO;
using System.Text;
using System.Reflection;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Threading;
using System.Globalization;
using System.Security.Cryptography;
using System.Drawing;
using System.Data;

using H2.NET.Business;
using H2.NET.Common;
using H2.NET.Data.Common;
using H2.NET.TaskRob;

namespace H2.NET
{
    public abstract class TaskPage : System.Web.UI.Page
    {
    #region 属性 Public
        int tick = 180000;  //180000= 3*60*1000
        private clsCommon comm = new clsCommon();
        /// <summary>
        /// 流程引擎 API
        /// </summary>
        public TaskAPI TaskAPI
        {
            get 
            {
                if (Session["TaskAPI" + (T == "P" ? Process + Incident + Step : TaskID)] == null)
                {
                    Session["TaskAPI" + (T == "P" ? Process + Incident + Step : TaskID)] = new TaskAPI();
                }

                return (TaskAPI)Session["TaskAPI" + (T == "P" ? Process + Incident + Step : TaskID)];
            }
        }

        /// <summary>
        /// 当前用户信息
        /// </summary>
        public t_User UserAPI
        {
            get
            {
                try
                {
                    //取得用户扩展信息
                    if (Session["UserAPI"] == null)
                    {
                        //取得用户
                        //string IdentityName = User.Identity.AuthenticationType.ToLower() == "negotiate"
                        //                    ? User.Identity.Name.ToLower().Replace(@"\", @"/").Replace("apacdom", "apac.ad.ici.com").Replace("d20", "adcnda.d20.intra").Replace("d30", "d30.intra").Replace("d10", "d10.intra")
                        //                    : (Request.Cookies["UserName"] == null || string.IsNullOrEmpty(Request.Cookies["UserName"].Value) ? "" : Util.Decrypt(Request.Cookies["UserName"].Value).ToLower());
                        string IdentityName = User.Identity.AuthenticationType.ToLower() == "negotiate"
                                            ?  comm.GetAccountFromDomain(User.Identity.Name.ToLower().Replace(@"\", @"/"))
                                            : (Request.Cookies["UserName"] == null || string.IsNullOrEmpty(Request.Cookies["UserName"].Value) ? "" : Util.Decrypt(Request.Cookies["UserName"].Value).ToLower());

                        Ultimus.OC.OrgChart oc = new Ultimus.OC.OrgChart();
                        Ultimus.OC.User ocUser = new Ultimus.OC.User();
                        oc.FindUser(IdentityName, "", 0, out ocUser);

                        t_User user = new t_User();
                        user.UserName = IdentityName;

                        //在当前用户存在的情况下
                        if (ocUser != null)
                        {
                            user.UserFullName = ocUser.strUserFullName;
                            user.Department = ocUser.strDepartmentName;
                            user.JobFunction = ocUser.strJobFunction;
                        }
                        user.Language = Request.Cookies["comm_language"] == null ? "en-us" : Request.Cookies["comm_language"].Value;   //en-us   zh-cn   Auto
                        Session["UserAPI"] = user;
                    }
                }
                catch (Exception)
                {
                }
                return (t_User)Session["UserAPI"];
            }
            set
            {
                Session["UserAPI"] = value;
            }
        }

        public TaskDB DBAPI
        {
            get
            {
                if (Session["TaskDB"] == null)
                {
                    Session["TaskDB"] = new TaskDB();
                }

                return (TaskDB)Session["TaskDB"];
            }
        }

        public TaskStore StoreAPI
        {
            get
            {
                if (Session["StoreAPI" + (T == "P" ? Process + Incident + Step : TaskID)] == null)
                {
                    Session["StoreAPI" + (T == "P" ? Process + Incident + Step : TaskID)] = new TaskStore(); 
                }

                return (TaskStore)Session["StoreAPI" + (T == "P" ? Process + Incident + Step : TaskID)];
            }
        }

        public void ClearStoreAPI()
        {
            Session["StoreAPI" + (T == "P" ? Process + Incident + Step : TaskID)] = null;
        }

        public string TaskID
        {
            get
            {
                return ViewState["TaskID"] == null ? "" : ViewState["TaskID"].ToString();
            }
            set
            {
                ViewState["TaskID"] = value;
            }
        }

        public string Process
        {
            get
            {
                return ViewState["Process"] == null ? "" : ViewState["Process"].ToString();
            }
            set
            {
                ViewState["Process"] = value;
            }
        }

        public string Incident
        {
            get
            {
                return ViewState["Incident"] == null ? "" : ViewState["Incident"].ToString();
            }
            set
            {
                ViewState["Incident"] = value;
            }
        }

        public string DraftID
        {
            get
            {
                return ViewState["DraftID"] == null ? "" : ViewState["DraftID"].ToString();
            }
            set
            {
                ViewState["DraftID"] = value;
            }
        }

        public string Step
        {
            get
            {
                return ViewState["Step"] == null ? "" : ViewState["Step"].ToString();
            }
            set
            {
                ViewState["Step"] = value;
            }
        }

        public string T
        {
            get
            {
                return ViewState["T"] == null ? "T" : ViewState["T"].ToString(); 
            }
            set
            {
                ViewState["T"] = value;
            }
        }

        public bool IsOverFlow
        {
            get
            {
                return ViewState["IsOverFlow"] == null ? false : (bool)ViewState["IsOverFlow"];
            }
            set
            {
                ViewState["IsOverFlow"] = value;
            }
        }

        public string RobUser
        {
            get
            {
                return TaskRob.OpenTasksInstance.OpenTasks.GetRobUser(TaskAPI.Process, TaskAPI.Incident, TaskAPI.Step);
            }
        }

        #endregion

    #region 重载 OnPreInit(页面初始化)
        /// <summary>
        /// 
        /// </summary>
        /// <param name="e"></param>
        protected override void OnPreInit(EventArgs e)
        {

            this.EnableEventValidation = false;
            base.OnPreInit(e);            
        }
        #endregion

    #region 重载 OnPreLoad(页面预加载)
        private string getQueryString(string url, int Position)
        {
            try
            {
                string[] s = url.Split('?');
                string[] s1 = s[1].Split('&');
                string[] s2 = s1[Position].Split('=');
                return s2[1];
            }
            catch
            { return ""; }
        }
        protected override void OnPreLoad(EventArgs e)
        {
            if (!IsPostBack)
            {
                Anthem.Manager.Register(this);
                string strTaskID = string.IsNullOrEmpty(Util.AppSettings("task")) ? Request.QueryString["TaskID"] : Util.AppSettings("task");
                string strDraftID = string.IsNullOrEmpty(Request.QueryString["DraftID"]) ? "" : Request.QueryString["DraftID"];

                #region TaskID 方式
                if (!string.IsNullOrEmpty(strTaskID))
                {
                    T = "T";

                    if (TaskID != strTaskID)
                    {
                        TaskID = strTaskID;
                        TaskAPI.Load(strTaskID, strDraftID);
                        Process = TaskAPI.Process;
                        Incident = TaskAPI.Incident.ToString();
                        DraftID = TaskAPI.DraftID;
                        Step = TaskAPI.Step;
                    }
                }
                #endregion

    #region PIS 方式
                else
                {
                    T = "P";
                    
                    string strProcess = Request.QueryString["p"];
                    string strIncident = Request.QueryString["i"];
                    string strStep = Request.QueryString["s"];
                    if (strProcess != null && strIncident != null && strStep != null)
                    if (strProcess.Length > 0 && strIncident.Length > 0 && strStep.Length > 0)
                    {
                        Request.ContentEncoding = Encoding.GetEncoding("GB2312");
                        Response.Charset = "utf-8";
                        Response.ContentEncoding = Encoding.UTF8;
                        Response.HeaderEncoding = Encoding.UTF8;
                        string q = Request.Url.ToString();
                        if (q.IndexOf(strProcess) <= 0 || q.IndexOf(strIncident) <= 0 || q.IndexOf(strStep) <= 0)
                        {
                            strProcess = getQueryString(q, 0);
                            strIncident = getQueryString(q, 1);
                            strStep = getQueryString(q, 2);
                        }
                        Request.ContentEncoding = Encoding.UTF8;
                        //System.Collections.Specialized.NameValueCollection nv = System.Web.HttpUtility.ParseQueryString(q, System.Text.Encoding.GetEncoding("utf-8")); 
                    }
                    
                    //如果是邮件通知里的链接打开的情况
                    if (!string.IsNullOrEmpty(strProcess))
                    {
                        if (Process != strProcess || Incident != strIncident || Step != strStep)
                        {
                            Process = strProcess;
                            Incident = strIncident;
                            Step = strStep;
                        }

                        //取得用户
                        //string IdentityName = User.Identity.AuthenticationType.ToLower() == "negotiate"
                        //                    ? User.Identity.Name.ToLower().Replace(@"\", @"/").Replace("apacdom", "apac.ad.ici.com").Replace("d20", "adcnda.d20.intra").Replace("d30", "d30.intra").Replace("d10", "d10.intra")
                        //                    : (Request.Cookies["UserName"] == null || string.IsNullOrEmpty(Request.Cookies["UserName"].Value) ? "" : Util.Decrypt(Request.Cookies["UserName"].Value).ToLower());
                        string IdentityName = User.Identity.AuthenticationType.ToLower() == "negotiate"
                                            ? comm.GetAccountFromDomain( User.Identity.Name.ToLower().Replace(@"\", @"/"))
                                            : (Request.Cookies["UserName"] == null || string.IsNullOrEmpty(Request.Cookies["UserName"].Value) ? "" : Util.Decrypt(Request.Cookies["UserName"].Value).ToLower());
                        bool flg = TaskAPI.Load(Process, Incident, Step, ref IdentityName);
                        if (!flg && (mdc_Recipient.process == Process & mdc_Recipient.recipient == IdentityName).Count<mdc_Recipient>() > 0)
                        {
                            //查找此步骤对应的第一个任务
                            IdentityName = "";
                            flg = TaskAPI.Load(Process, Incident, Step, ref IdentityName);

                            //非当前用户的任务，拒绝提交表单
                            TaskAPI.IsAllowSubmit = false;
                            if (!flg) { Response.Redirect(ResolveUrl("~/ERRTask.aspx")); }
                        }

                        if (!flg)
                        {
                            Response.Redirect(ResolveUrl("~/ERRNoRight.aspx"));
                        }

                        TaskID = TaskAPI.TaskID;
                    }
                }
    #endregion

    #region 任务抢占
                if (TaskAPI.IsLoaded && !TaskAPI.IsBeginStep && TaskAPI.IsAllowSubmit)
                {
                    t_MinResp mr = (t_MinResp.processname == TaskAPI.Process & t_MinResp.steplabel == TaskAPI.Step & t_MinResp.minresp > 0).ListFirst<t_MinResp>(Storage.Context2, t_MinResp.processversion.Desc);
                    if (mr != null)
                    {
                        TaskRob.OpenTasksInstance.OpenTasks.SetTaskOpen(TaskAPI.Process, TaskAPI.Incident, TaskAPI.Step, mr.Minresp, UserAPI.UserName, UserAPI.UserFullName);

                        bool isOverFlow = TaskRob.OpenTasksInstance.OpenTasks.IsOverFlow(TaskAPI.Process, TaskAPI.Incident, TaskAPI.Step, UserAPI.UserName);
                        if (isOverFlow)
                        {
                            TaskAPI.IsAllowSubmit = false;
                        }
                        else
                        {
                            Anthem.Manager.RegisterClientScriptBlock(typeof(Page)
                                , "RobTick"
                                , @"<script type='text/javascript'>var RobTick_timer = null;function RobTick(){if (typeof(RobTick_timer) != 'undefined' && RobTick_timer != null){clearTimeout(RobTick_timer);RobTick_timer = null;}RobTick_timer = setTimeout(function() { Anthem_InvokePageMethod('RobTick', [], function() { });}," + tick.ToString() + ");} RobTick();</script>");

                            Anthem.Manager.RegisterClientScriptBlock(typeof(Page)
                                , "RobClose"
                                , @"<script language='javascript' type='text/javascript'>function window.onunload() {if (typeof(RobTick_timer) != 'undefined' && RobTick_timer != null){clearTimeout(RobTick_timer);RobTick_timer = null;} Anthem_InvokePageMethod('RobClose', [], function() { });}</script>");
                        }

                        IsOverFlow = isOverFlow;
                    }
                    else
                    {
                        TaskRob.OpenTasksInstance.OpenTasks.SetTaskClose(TaskAPI.Process, TaskAPI.Incident, TaskAPI.Step);
                    }
                }
    #endregion
            }

            base.OnPreLoad(e);
        }
    #endregion

    #region 重载 OnInit(页面加载)
        /// <summary>
        /// 
        /// </summary>
        /// <param name="e"></param>
        protected override void OnInit(EventArgs e)
        {
            RegisterScriptInclude(this, ResolveUrl("~/Resource/Js/Common.js"));
            base.OnInit(e);
        }
    #endregion

    #region 重载 OnError(异常处置)
        /// <summary>
        /// 
        /// </summary>
        /// <param name="e"></param>
        protected override void OnError(EventArgs e)
        {
            Exception ex = Server.GetLastError();
            string path = Util.AppSettings("log").Replace(".log", "") + " " + System.DateTime.Now.ToString("yyyy-MM-dd") + ".log";
            TaskDB.Log(path, false, "Start---------------------------------------------");
            TaskDB.Log(path, false, string.Format("TaskID={0}; Process={1}; Incident={2}; Step={3};", TaskID, Process, Incident, Step));
            TaskDB.Log(path, false, ex.ToString());
            TaskDB.Log(path, false, "End-----------------------------------------------");

            ////Logging.Error("BasePage Catch The Exception.");
            ////Context.ClearError();
            ////Server.Transfer("~/ErrorStatus.aspx", true);

            base.OnError(e);
        }
    #endregion

    #region 重载 InitializeCulture(多语言)
        /// <summary>
        /// 多语言
        /// </summary>
        protected override void InitializeCulture()
        {
            string strTaskID = string.IsNullOrEmpty(Util.AppSettings("task")) ? Request.QueryString["TaskID"] : Util.AppSettings("task");

    #region TaskID 方式
            if (!string.IsNullOrEmpty(strTaskID))
            {
                //检查使用测试账号调试
                if (!string.IsNullOrEmpty(Util.AppSettings("user")))
                {
                    Session["SessionUser"] = Util.AppSettings("user");
                }

                //检查用户是否登陆
                if (Session["SessionUser"] != null && Session["SessionUser"].ToString().Split('~').Length >= 5)
                {
                    string[] SplitUser = Page.Session["SessionUser"].ToString().Split('~');

                    t_User user = new t_User();
                    user.UserName = SplitUser[0];
                    user.UserFullName = SplitUser[1];
                    user.Department = SplitUser[2];
                    user.JobFunction = SplitUser[3];
                    user.Language = SplitUser[4];                               //en-us   zh-cn   Auto
                    user.Mail = SplitUser.Length >= 6 ? SplitUser[5] : "";   //mail
                    UserAPI = user;
                }
            }
    #endregion

    #region PIS 方式
            else
            {
                //取得用户扩展信息
                if (UserAPI == null)
                {
                    //取得用户
                    //string IdentityName = User.Identity.AuthenticationType.ToLower() == "negotiate"
                    //                    ? User.Identity.Name.ToLower().Replace(@"\", @"/").Replace("apacdom", "apac.ad.ici.com").Replace("d20", "adcnda.d20.intra").Replace("d30", "d30.intra").Replace("d10", "d10.intra")
                    //                    : (Request.Cookies["UserName"] == null || string.IsNullOrEmpty(Request.Cookies["UserName"].Value) ? "" : Util.Decrypt(Request.Cookies["UserName"].Value).ToLower());
                    string IdentityName = User.Identity.AuthenticationType.ToLower() == "negotiate"
                                        ? comm.GetAccountFromDomain ( User.Identity.Name.ToLower().Replace(@"\", @"/"))
                                        : (Request.Cookies["UserName"] == null || string.IsNullOrEmpty(Request.Cookies["UserName"].Value) ? "" : Util.Decrypt(Request.Cookies["UserName"].Value).ToLower());
                    //Ultimus.OC.OrgChart oc = new Ultimus.OC.OrgChart();
                    //Ultimus.OC.User ocUser = new Ultimus.OC.User();
                    //oc.FindUser(IdentityName, "", 0, out ocUser);

                    t_User user = new t_User();
                    user.UserName = IdentityName;
                    string sql = string.Format("select rtrim(a.fullname) as fullname,rtrim(a.jobfunction) as jobfuntion,rtrim(b.name) as deptname from jobs a,departments b where a.name='{0}' and a.deptid=b.id order by isprimary desc", user.UserName);
                    DBAPI.Storage("bpmDB");
                    DataTable dt = DBAPI.Query(sql);
                    if(dt.Rows.Count > 0)
                    {
                        user.UserFullName = dt.Rows[0]["fullname"].ToString();
                        user.Department   = dt.Rows[0]["jobfuntion"].ToString();
                        user.JobFunction  = dt.Rows[0]["deptname"].ToString();
                    }

                    ////在当前用户存在的情况下
                    //if (ocUser != null)
                    //{
                    //    user.UserFullName = ocUser.strUserFullName;
                    //    user.Department = ocUser.strDepartmentName;
                    //    user.JobFunction = ocUser.strJobFunction;
                    //}

                    UserAPI = user;
                    UserAPI.Language = Request.Cookies["comm_language"] == null ? "en-us" : Request.Cookies["comm_language"].Value;   //en-us   zh-cn   Auto
                }
            }
    #endregion

            //多语言切换
            if (UserAPI != null)
            {
                Thread.CurrentThread.CurrentUICulture = new CultureInfo(UserAPI.Language == null ? "en-us" : UserAPI.Language);
                Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture(UserAPI.Language == null ? "en-us" : UserAPI.Language);
            }

            base.InitializeCulture();
        }
    #endregion

    #region 事件 心跳注册、关闭(任务抢占)
        [Anthem.Method]
        protected void RobTick()
        {
            TaskDB.Log("", false, "TaskPage => RobTick:" + System.DateTime.Now.ToString("yyyyMMddHHmmss"));
            TaskRob.OpenTasksInstance.OpenTasks.UpldateTaskStatus(true, TaskAPI.Process, TaskAPI.Incident, TaskAPI.Step, UserAPI.UserName, UserAPI.UserFullName);
            Anthem.Manager.AddScriptForClientSideEval("RobTick();");
        }

        [Anthem.Method]
        protected void RobClose()
        {
            TaskDB.Log("", false, "TaskPage => RobClose:" + System.DateTime.Now.ToString("yyyyMMddHHmmss"));
            TaskRob.OpenTasksInstance.OpenTasks.UpldateTaskStatus(false, TaskAPI.Process, TaskAPI.Incident, TaskAPI.Step, UserAPI.UserName, UserAPI.UserFullName);
        }
    #endregion

    #region 方法 RegisterScriptInclude(脚本文件注册)
        /// <summary>
        /// 
        /// </summary>
        /// <param name="control"></param>
        /// <param name="script"></param>
        private static void RegisterScriptInclude(Control control, string script)
        {
            if (!control.Page.IsStartupScriptRegistered(script))
            {
                control.Page.RegisterClientScriptBlock(control.GetType().FullName, "<script language=\"javascript\" type=\"text/javascript\" src=\"" + script + "\"></script>\n");
            }
        }
    #endregion

    #region 方法 SetEnable(设置控件禁启用)
        //设置控件禁启用
        /// <summary>
        /// 
        /// </summary>
        /// <param name="IsEnable"></param>
        /// <param name="WebControl"></param>
        /// 

        protected enum ControlStatus { Enable = 1, Disable = 2, Display = 3 };
        private void SetEnableAdvanced(bool IsEnable, params WebControl[] WebControl)
        {
            foreach (object ctl in WebControl)
            {
                switch (ctl.ToString().ToLower())
                {
                    case "anthem.panel":
                        foreach (object c1 in ((WebControl)ctl).Controls)
                        {
                            switch (c1.ToString().ToLower())
                            {
                                case "anthem.label":
                                    //((Anthem.Label)c1).ForeColor = Color.Empty;
                                    break;
                                case "anthem.textbox":
                                    if (((WebControl)ctl).FindControl(((Anthem.TextBox)c1).ID + "_L") != null)
                                    {
                                        ((Anthem.TextBox)c1).Visible = IsEnable;
                                        ((Anthem.Label)((WebControl)ctl).FindControl(((Anthem.TextBox)c1).ID + "_L")).Text = ((Anthem.TextBox)c1).Text;
                                        //((Anthem.Label)((WebControl)ctl).FindControl(((Anthem.TextBox)c1).ID + "_L")).Width = 100;
                                        ((Anthem.Label)((WebControl)ctl).FindControl(((Anthem.TextBox)c1).ID + "_L")).Visible = !IsEnable;
                                    }
                                    else { ((Anthem.TextBox)c1).Enabled = IsEnable; }
                                    break;
                                case "anthem.dropdownlist":
                                    if (((WebControl)ctl).FindControl(((Anthem.DropDownList)c1).ID + "_L") != null)
                                    {
                                        ((Anthem.DropDownList)c1).Visible = IsEnable;
                                        ((Anthem.Label)((WebControl)ctl).FindControl(((Anthem.DropDownList)c1).ID + "_L")).Text = ((Anthem.DropDownList)c1).SelectedItem.Text;
                                        //((Anthem.Label)((WebControl)ctl).FindControl(((Anthem.DropDownList)c1).ID + "_L")).Width = 100;
                                        ((Anthem.Label)((WebControl)ctl).FindControl(((Anthem.DropDownList)c1).ID + "_L")).Visible = !IsEnable;
                                    }
                                    else { ((Anthem.DropDownList)c1).Enabled = IsEnable; }
                                    break;
                                case "h2.net.controls.dialog":
                                    ((WebControl)c1).Enabled = IsEnable;
                                    break;
                                case "h2.net.controls.gridview":
                                    ((WebControl)c1).Enabled = IsEnable;
                                    break;
                                case "anthem.button":
                                    ((Anthem.Button)c1).Enabled = IsEnable;
                                    break;
                                default:
                                    if (c1.ToString().IndexOf("Literal") < 0) ((WebControl)c1).Enabled = IsEnable;
                                    break;
                            }
                        }
                        break;
                    default:
                        ((WebControl)ctl).Enabled = IsEnable;
                        break;
                }
            }
        }
        protected void SetEnable(ControlStatus Status, params WebControl[] WebControl)
        {
            switch (Status)
            { 
                case ControlStatus.Enable:
                    SetEnableAdvanced(true, WebControl);
                    break;
                case ControlStatus.Disable:
                    SetEnableAdvanced(false, WebControl);
                    break;
                case ControlStatus.Display:
                    SetEnableAdvanced(false, WebControl);
                    break;
                default :
                    break;
            }
        }
        protected void SetEnable(bool IsEnable, params WebControl[] WebControl)
        {
            foreach (object ctl in WebControl)
            {
                ((WebControl)ctl).Enabled = IsEnable;
            }
        }
    #endregion

    #region 方法 SetVisible设置控件显示隐藏
        /// <summary>
        /// 
        /// </summary>
        /// <param name="IsEnable"></param>
        /// <param name="WebControl"></param>
        protected void SetVisible(bool IsEnable, params WebControl[] WebControl)
        {
            foreach (WebControl wc in WebControl)
            {
                wc.Visible = IsEnable;
                wc.Attributes["v"] = IsEnable ? "1" : "0";
            }
        }
    #endregion

    #region 方法 SetEmptyValue 清空控件值
        protected void SetEmptyValue(params WebControl[] WebControl)
        {
            foreach (WebControl ctl in WebControl)
            {
                switch (ctl.GetType().Name)
                {
                    case "TextBox":
                        ((TextBox)ctl).Text = "";
                        break;
                    case "DropDownList":
                        ((DropDownList)ctl).SelectedIndex = -1;
                        break;
                    case "Label":
                        ((Label)ctl).Text = "";
                        break;
                    case "CheckBox":
                        ((CheckBox)ctl).Checked = false;
                        break;
                    case "CheckBoxList":
                        CheckBoxList cbls = (CheckBoxList)ctl;
                        for (int i = 0; i < cbls.Items.Count; i++)
                        {
                            cbls.Items[i].Selected = false;
                        }
                        break;
                    case "Calendar":
                        ((TextBox)ctl).Text = "";
                        break;
                    case "Dialog":
                        ((TextBox)ctl).Text = "";
                        break;
                }
            }
        }
    #endregion

    #region 方法 SetForeColor(设置前景颜色)
        protected void SetForeColor(Color Color, params WebControl[] WebControl)
        {
            foreach (WebControl ctl in WebControl)
            {
                ctl.ForeColor = Color;
            }
        }
    #endregion

    #region 方法 Validation 数据验证检查
        public static List<string> Validation(List<Regular> listRegular)
        {
            List<string> strlist = new List<string>();

            foreach (Regular reg in listRegular)
            {
                if (reg.Match == RegularExp.NotEmpty)
                {
                    if (string.IsNullOrEmpty(reg.Value.ToString()))
                    {
                        strlist.Add(reg.Message);
                    }
                }
                else
                {
                    System.Text.RegularExpressions.Regex strReg = new System.Text.RegularExpressions.Regex(reg.Match);
                    if (!strReg.IsMatch(reg.Value.ToString()))
                        strlist.Add(reg.Message);
                }

            }
            return strlist;
        }

        public static List<string> Validation(string regstr, List<Regular> listRegular)
        {
            List<string> strlist = new List<string>();

            foreach (Regular reg in listRegular)
            {
                if (regstr == RegularExp.NotEmpty)
                {
                    if (string.IsNullOrEmpty(reg.Value.ToString()))
                    {
                        strlist.Add(reg.Message);
                    }
                }
                else
                {
                    System.Text.RegularExpressions.Regex strReg = new System.Text.RegularExpressions.Regex(regstr);
                    if (!strReg.IsMatch(reg.Value.ToString()))
                        strlist.Add(reg.Message);
                }

            }
            return strlist;
        }

        public static List<string> Validation(string regstr, params Regular[] regs)
        {
            List<string> strlist = new List<string>();
            foreach (Regular reg in regs)
            {
                if (regstr == RegularExp.NotEmpty)
                {
                    if (string.IsNullOrEmpty(reg.Value.ToString()))
                    {
                        strlist.Add(reg.Message);
                    }
                }
                else
                {
                    System.Text.RegularExpressions.Regex strReg = new System.Text.RegularExpressions.Regex(regstr);
                    if (!strReg.IsMatch(reg.Value.ToString()))
                        strlist.Add(reg.Message);
                }
            }
            return strlist;
        }
    #endregion

    #region 方法 CombineMessage 数据验证检查
        public static string CombineMessage(List<string> list)
        {
            string str = "<table>";
            str += "<tr><td align='left'>&nbsp;&nbsp;<a style='cursor:hand;color:blue;' onclick='DeleteDiv();'>[关闭]</a></td></tr>";
            foreach (string var in list)
            {
                str += string.Format("<tr><td align='left' style='color:red;'>{0}</td><tr>", var);
            }

            str += "<tr><td align='left'>&nbsp;&nbsp;<a style='cursor:hand;color:blue;' onclick='DeleteDiv();'>[关闭]</a></td></tr>";
            str += "</table>";

            return str;
        }
    #endregion

    #region 方法 RegularCheck 是否验证检查
        public static void akzo_RegularCheck(ref List<Regular> regs, string match, WebControl wc, object obj, string message)
        {
            if (wc.ForeColor == Color.Blue && wc.Attributes["v"] == "1")
            {
                regs.Add(new Regular(match, obj, message));
            }
        }
        public static void RegularCheck(ref List<Regular> regs, Color clr, string match, WebControl wc, object obj, string message)
        {
            if (wc.ForeColor == clr)
            {
                regs.Add(new Regular(match, obj, message));
            }
        }
        public static void RegularCheck(ref List<Regular> regs, bool isCheck, string match, object obj, string message)
        {
            if (isCheck)
            {
                regs.Add(new Regular(match, obj, message));
            }
        }
    #endregion

    #region 方法 IsInGroup_s(判断是否在指定工作组)
        public void IsInGroup_s(string iUserName, string[] iGroupName, ref string[] oIsExist)
        {
            try
            {
                //初始化
                for (int i = 0; i < oIsExist.Length; i++)
                {
                    oIsExist[i] = "0";
                }

                string iGroups = "";
                iUserName = string.IsNullOrEmpty(iUserName) ? "" : iUserName.Replace("'", "''");

                for (int i = 0; i < iGroupName.Length; i++)
                {
                    iGroups += (i == 0 ? "'" : ",'") + iGroupName[i] + "'";
                }

                DataTable dt = new DataTable();
                using (TaskDB clsDB = new TaskDB())
                {
                    string strSQL = "";
                    strSQL += "select distinct rtrim(gname) as gname from groups where gname in(" + iGroups + ") and member in(";

                    strSQL += "select (rtrim(b.name) + rtrim('*') + rtrim(a.jobfunction)) as groupmember";
                    strSQL += "  from jobs a, departments b";
                    strSQL += " where a.deptid = b.id";
                    strSQL += "   and lower(a.name) = lower('" + iUserName + "')";
                    strSQL += "   and a.jobtype in (2, 4, 64)";
                    strSQL += " union all ";
                    strSQL += "select (rtrim(b.name) + rtrim('*') + rtrim(a.jobfunction)) as groupmember";
                    strSQL += "  from jobs a, departments b";
                    strSQL += " where a.deptid = b.id";
                    strSQL += "   and a.id in (select supervisorid";
                    strSQL += "                  from jobs";
                    strSQL += "                 where lower(jobs.name) = lower('" + iUserName + "')";
                    strSQL += "                   and jobs.jobtype = 64)";

                    strSQL += " union all ";
                    strSQL += "select '" + iUserName + "' as groupmember";
                    strSQL += " union all ";

                    strSQL += "select rtrim(b.name) as groupmember";
                    strSQL += "  from jobs a, departments b";
                    strSQL += " where a.deptid = b.id";
                    strSQL += "   and lower(a.name) = lower('" + iUserName + "')";
                    strSQL += "   and a.jobtype in (2, 4, 64)";
                    strSQL += ")";

                    clsDB.Storage("bpmDB");
                    dt = clsDB.Query(strSQL);
                }

                //判断是否在指定工作组
                for (int i = 0; i < iGroupName.Length; i++)
                {
                    if (string.IsNullOrEmpty(iGroupName[i]))
                    {
                        continue;
                    }

                    for (int j = 0; j < dt.Rows.Count; j++)
                    {
                        if (iGroupName[i] == dt.Rows[j]["gname"].ToString())
                        {
                            oIsExist[i] = "1";
                            break;
                        }
                    }
                }
            }
            catch (Exception)
            {
            }
        }
    #endregion
    }

}